import { delay, postMsg, buildMsgHandler, postFilters } from '../utils.js';

let baseInfoCache;

async function doLogin({ companyInfo }) {
  if (location.href.includes('sso/login')) {
    await delay();
    window.layer.closeAll();
    await delay(500);

    const { nationalTaxAccount, nationalTaxId, nationalTaxPass, taxStaffPhone = '' } =
      companyInfo || {};

    const scope = window.angular.element(document.querySelector('#app')).scope();
    scope.$apply(() => {
      scope.login.nsr.yh.userName = nationalTaxAccount || nationalTaxId;
      scope.login.nsr.yh.passWord = nationalTaxPass;
      scope.login.nsr.yh.phone = taxStaffPhone;
    });
  }
}


function postKjzd() {
  let institutionCode = '';
  const clientName = document.querySelector('#sbbName').innerText;
  if (!clientName.includes('企业会计准则')) {
    throw new Error('不支持的财务报表');
  }

  if (clientName.includes('小企业会计准则')) {
    institutionCode = 2;
  } else if (clientName.includes('企业会计准则')) {
    institutionCode = 1;
  }

  postMsg('fixTaxGovInfo', { institutionCode });
}

function beforeCwbb() {
  const title = $(
    '#divSheetlist>li.current_selected_BD',
    window.frames.frmMain.document
  ).text();

  let type = 'balance';
  if (title.includes('资产负债表')) {
    type = 'balance';
  } else if (title.includes('现金流量表')) {
    type = 'cash';
  } else if (title.includes('利润表')) {
    type = 'profit';
  }

  postFilters(type);
  postKjzd();
}

console.info('插件已加载');
$(window).ready(function () {
  postMsg('getBaseInfo');

  const pathname = window.location.pathname;
  $('#frmMain').on('load', () => {
    switch (pathname) {
      // 企业所得税年报
      case '/sbzx-cjpt-web/biz/sb/qysds_a_18nd':
        postFilters('hsqj');
        break;
      // 财务报表
      case '/sbzx-cjpt-web/biz/cb/cwbb_xqykjzz':
      case '/sbzx-cjpt-web/biz/cb/cwbb_qykjzz':
        beforeCwbb();
        break;
      default:
        break;
    }
  });

  const msgHandler = buildMsgHandler({
    baseInfo: baseInfoCache,
    onBaseInfo: doLogin,
  });
  window.addEventListener('message', msgHandler, false);
});
